<?php
class Func_Log
{
    const LEVEL_DEBUG = 0;
    const LEVEL_INFO = 1;
    const LEVEL_WARNING = 2;
    const LEVEL_ERROR = 3;

    public static function write($module_name, $notice_header, $notice_body = '', $MSG_LEVEL = 1)
    {
        if (RUNTIME_ENV == "rls" && $MSG_LEVEL < 1) {
            return false;
        }
        ini_set('date.timezone', 'Asia/Shanghai');
        $path = LIBRARY_DIR . '/../logs/';
        if (!file_exists($path)) {
            @mkdir($path, 0755);
        }
        $date_str = date('Y-m-d');
        $date_fmt = date('Y-m-d H:i:s', time());
        $path = $path . $module_name . '/';
        if (!file_exists($path)) {
            @mkdir($path, 0755);
        }
        $filepath = $path . $date_str . '.log';
        if (!$fp = @fopen($filepath, 'ab')) {
            return false;
        }

        $level_msg = "[UNDEFINE]";
        switch ($MSG_LEVEL) {
            case Func_Log::LEVEL_DEBUG:
                $level_msg = "[DEBUG]";
                break;
            case Func_Log::LEVEL_INFO:
                $level_msg = "[INFO]";
                break;
            case Func_Log::LEVEL_WARNING:
                $level_msg = "[WARNING]";
                break;
            case Func_Log::LEVEL_ERROR:
                $level_msg = "[ERROR]";
                break;
            default:
        }
        // 获取文件名称和文件行号
        $log = "Current File : %s : %s" . PHP_EOL;
        $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
        $inFile = sprintf($log, trim($backtrace[0]['file']), $backtrace[0]['line']);

        $message = PHP_EOL . $date_fmt . '::' . PHP_EOL . $inFile . str_pad($level_msg, 10, " ", STR_PAD_RIGHT) . $notice_header . '::' . $notice_body;
        flock($fp, LOCK_EX);
        fwrite($fp, $message);
        flock($fp, LOCK_UN);
        fclose($fp);
        @chmod($filepath, 0755);
        return true;
    }
}
